// 弹窗复选
import React from 'react';
import {
  Modal,
  Space,
  Select,
  DatePicker,
  Button,
  Upload,
  Form,
  message,
  ConfigProvider,
} from 'antd';
import { useDebounceFn } from 'ahooks';
import moment from 'moment';
import * as XLSX from 'xlsx';
import _ from 'lodash';

import {
  CalendarOutlined,
  CloseOutlined,
  DownloadOutlined,
  FileTextOutlined,
} from '#/utils/antdIcons.js';
import TRNotification from '#/utils/notification.js';
import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components/index.js';

import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import { planOptions, YearOptions, OPTION_KEY } from '../../helper.js';
import CheckedList from '../CheckedList';
import { MyStations } from '../MyStations';
import styles from './index.less';
import {
  querypowerGenerationData,
  getStationsByIds,
  saveYearToMonthPowerGenerationPlan,
  useNewServers,
} from '../../services.js';
import { export_json_sheets_to_excel } from '@/utils/fileExport.js';
import zhCN from 'antd/lib/locale/zh_CN';

const MySelect = (props: any) => {
  const { value = [], onChange, options = [] } = props;
  return (
    <div style={{ position: 'relative' }}>
      <Select
        showSearch={false}
        value={value}
        options={options}
        style={{ width: 120, fontSize: 12 }}
        placeholder="选择参考年份"
        mode="multiple"
        maxTagCount={0}
        maxTagTextLength={2}
        onChange={onChange}
        dropdownRender={() =>
          options.length ? (
            <CheckedList options={options} onChange={onChange} value={value} />
          ) : (
            <TRDefault type="emptysm" />
          )
        }
      />
      <CalendarOutlined className={styles.icon_calendar} />
    </div>
  );
};

const ModalComponent = (props: any) => {
  const {
    stations,
    stationTree,
    optionAll,
    onPress,
    buttonPermissions,
    getNewTableData,
    defaultItem,
    treeData,
    province,
  } = props;
  const [uploadData, setUploadData] = React.useState<any>([]),
    [visible, setVisible] = React.useState(true),
    [showBtn, setShowBtn] = React.useState(true),
    [referencePowerOption, setReferencePowerOption] = React.useState(
      YearOptions(moment().format('YYYY')),
    ),
    [saveType, setSaveType] = React.useState(0),
    [btnLoding, setBtnLoding] = React.useState(false),
    [fileError, setFileError] = React.useState(true),
    [finalyFile, setFinalyFile] = React.useState<any>([]), //最终保存文件,
    [form] = Form.useForm(),
    [currentProvinceInfo, setCurrentProvinceInfo] = React.useState<any>(),
    [curMarketId, setCurMarketId] = React.useState(''); //缓存当前选中的marketId

  const disabledPlanDate = (current: any) => {
    return current && current < moment().endOf('day');
  };
  //保留小数位数
  const _parseFloat = (val: any, length: number) => {
    return parseFloat(parseFloat(val).toFixed(length));
  };
  //文件校验未通过 展示红字提示
  React.useEffect(() => {
    if (!fileError) {
      setUploadData([{ ...uploadData[0], status: 'error', response: '校验未通过' }]);
      setSaveType(0);
      setBtnLoding(false);
    }
  }, [fileError]);

  React.useEffect(() => {
    // province 是父组件传的交易中心下拉选项
    if (province.length > 0) {
      // 选第一个交易中心作为默认
      changeMarketId(province[0]?.value);
      setCurMarketId(province[0]?.value);
    }
  }, [province]);

  const _beforeUpload = (file: any) => {
    setFileError(true);
    setBtnLoding(true);
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    fileReader.onload = async (event) => {
      const { result }: any = event.target;
      // 以二进制流方式读取得到整份excel表格对象
      const workbook = XLSX.read(result, { type: 'binary', header: 1 });
      let beforeData = '', //分解比例对应年计划
        beforeyearDate = '', //对应年份
        beforeUnitID = ''; //交易单元ID
      for (const sheet in workbook.Sheets) {
        const _temp = XLSX.utils
          .sheet_to_json(workbook.Sheets[sheet])
          .sort(
            (a: any, b: any) =>
              (
                Object.entries(b).find((t: any) => t[0].replaceAll(' ', '') === '')?.[1] as any
              )?.substring(0, 4) -
              (
                Object.entries(a).find((t: any) => t[0].replaceAll(' ', '') === '')?.[1] as any
              )?.substring(0, 4),
          );
        //校验首行数据
        if (_temp.length === 12) {
          //月计划分时间段
          const unitID = stations.find((t: any) => t.label === sheet)?.value;
          const MarketId = stations.find((t: any) => t.label === sheet)?.marketId;
          if (!unitID) {
            message.warning(`交易单元不存在！`);
            setFileError(false);
            return false;
          }
          const colData = _temp;
          //校验装机容量
          const res = await getStationsByIds({ stationIds: [unitID] }, MarketId);
          if (res?.statusCode === HttpCode.SUCCESS) {
            let isNaN = false;

            colData.forEach((t: any) => {
              const isValidDecimal = (value: any) => {
                // 正则表达式匹配小数点后最多三位的阿拉伯数字
                return /^(\d+(\.\d{1,3})?)$/.test(value);
              };
              const allValid = Object.entries(t).reduce((acc, [key, value]) => {
                if (key === '') return acc;
                return acc && isValidDecimal(value);
              }, true);
              if (!allValid) {
                isNaN = true;
              }
            });
            if (isNaN) {
              message.warning('仅支持小数点后三位的阿拉伯数字');
              setFileError(false);
              return false;
            } else {
              let yearDate = '';
              // 数据格式转换
              const transformData = colData.reduce(
                (
                  acc: {
                    planHour: string;
                    planMonth: any; // 月份转换
                    planValue: unknown; // 保留原始值
                  }[],
                  monthData: { [x: string]: any; ''?: any },
                ) => {
                  // 获取月份（从空字符串键中提取）
                  const month = monthData[''];
                  // 移除月份键，只保留时间数据
                  const { '': _, ...hourData } = monthData;
                  // 遍历24小时数据
                  Object.entries(hourData).forEach(([hour, value]) => {
                    yearDate = month.substring(0, 4);
                    acc.push({
                      planHour: hour.startsWith('0') ? hour.charAt(1) : hour.substring(0, 2),
                      planMonth: month.match(/年(.*?)月/)[1], // 月份转换
                      planValue: value, // 保留原始值
                    });
                  });
                  return acc;
                },
                [] as { planHour: string; planMonth: string; planValue: string }[],
              );
              //  根据unitID获取marketid
              const maridarr = province.filter(
                ({ stations }: { stations: { stationId: string }[] }) => {
                  return stations.some((station) => station.stationId === unitID);
                },
              );
              setSaveType(3);
              finalyFile.push({
                unitID,
                yearDate,
                count: 0,
                colData: transformData,
                marketId: maridarr[0].value,
              });
              setFinalyFile(finalyFile);
            }
          } else {
            message.warning('获取装机容量失败');
            setFileError(false);
            return false;
          }
        } else {
          if (_temp?.[0] && !Object.keys(_temp?.[0])?.every((v) => v.trim())) {
            const colData = _temp?.[0];
            const isNotYearPlan = Object.keys(colData).some((t: any) => t.includes('月')); //月计划 | 月分解比例
            const isNotMonthPlan = Object.entries(colData).some((t: any) => {
              if (t[0].replaceAll(' ', '') === '') {
                return t[1].includes('比例');
              }
            }); //分解比例
            if (!isNotYearPlan) {
              //年计划
              const yearPower = _parseFloat(colData['计划电量'], 3);
              if (String(yearPower) === 'NaN') {
                message.warning('仅支持小数点后三位的阿拉伯数字');
                setFileError(false);
                return false;
              }
              const unitID = stations.find((t: any) => t.label === sheet)?.value;
              const MarketId = stations.find((t: any) => t.label === sheet)?.marketId;
              if (!unitID) {
                message.warning(`交易单元不存在！`);
                setFileError(false);
                return false;
              }
              //校验装机容量
              const res = await getStationsByIds({ stationIds: [unitID] }, MarketId);
              if (res?.statusCode === HttpCode.SUCCESS) {
                if (
                  _parseFloat(yearPower, 3) >
                  _parseFloat(res.data?.[0]?.stationCapacity * 10 * 24 * 365, 3)
                ) {
                  message.warning('计划电量超过最大上限');
                  setFileError(false);
                  return false;
                } else {
                  //校验通过
                  beforeData = _temp?.[0]['计划电量'];
                  beforeyearDate = (
                    Object.entries(_temp?.[0]).find(
                      (t: any) => t[0].replaceAll(' ', '') === '',
                    )?.[1] as any
                  ).substring(0, 4);
                  beforeUnitID = unitID;
                }
              } else {
                message.warning('获取装机容量失败');
                setFileError(false);
                return false;
              }
            } else if (isNotMonthPlan) {
              //分解比例
              let num = 0;
              Object.entries(colData).forEach((t: any) => {
                if (t[0].replaceAll(' ', '') !== '') {
                  num = _parseFloat(parseFloat(t[1]) + num, 4);
                }
              });
              if (num !== 1) {
                message.warning('月度分解比例≠100%');
                setFileError(false);
                return false;
              } else {
                setSaveType(1);
                finalyFile.push({ beforeData, beforeyearDate, beforeUnitID, colData });
                setFinalyFile(finalyFile);
              }
            } else if (isNotYearPlan && !isNotMonthPlan) {
              //月计划
              const unitID = stations.find((t: any) => t.label === sheet)?.value;
              const MarketId = stations.find((t: any) => t.label === sheet)?.marketId;
              if (!unitID) {
                message.warning(`交易单元不存在！`);
                setFileError(false);
                return false;
              }
              //校验装机容量
              const res = await getStationsByIds({ stationIds: [unitID] }, MarketId);
              if (res?.statusCode === HttpCode.SUCCESS) {
                let isOverflow = false,
                  isNaN = false,
                  count = 0;
                Object.values(OPTION_KEY).some((t: any, i: number) => {
                  if (String(parseFloat(colData[`${i + 1}月`])) === 'NaN') {
                    isNaN = true;
                    return true;
                  }
                  if (
                    _parseFloat(colData[`${i + 1}月`], 3) >
                    _parseFloat(
                      res.data[0].stationCapacity * 24 * 10 * moment().month(i).daysInMonth(),
                      3,
                    )
                  ) {
                    isOverflow = true;
                    return true;
                  }
                  count += _parseFloat(colData[`${i + 1}月`], 3);
                });
                if (isNaN) {
                  message.warning('仅支持小数点后三位的阿拉伯数字');
                  setFileError(false);
                  return false;
                } else if (isOverflow) {
                  message.warning('计划电量超过最大上限');
                  setFileError(false);
                  return false;
                } else {
                  //校验通过
                  const yearDate = (
                    Object.entries(_temp?.[0]).find(
                      (t: any) => t[0].replaceAll(' ', '') === '',
                    )?.[1] as any
                  )?.substring(0, 4);
                  setSaveType(2);
                  finalyFile.push({ unitID, yearDate, count: _parseFloat(count, 3), colData });
                  setFinalyFile(finalyFile);
                }
              } else {
                message.warning('获取装机容量失败');
                setFileError(false);
                return false;
              }
            }
          } else {
            message.warning('请上传正确模板');
            setFileError(false);
            return false;
          }
        }
      }
      setBtnLoding(false); //确认按钮状态
    };
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(file);
    return false;
  };
  const onDateChange = async (data: any) => {
    const temp = YearOptions(moment(data).format('YYYY'));
    setReferencePowerOption(data ? temp : []);
    form.setFieldsValue({ referenceYear: [] });
  };

  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  const _onOk = () => {
    if (btnLoding) return;
    if (saveType === 1) {
      setBtnLoding(true);
      //年计划
      //月分解比例
      finalyFile.forEach(async (item: any) => {
        const param: any = {
          monthEle: {},
          stationId: item.beforeUnitID,
          valueType: 'proportion',
          year: item.beforeyearDate,
          publish: true,
          yearEle: item.beforeData,
        };

        if (useNewServers.includes(curMarketId)) {
          param.marketId = curMarketId;
        }

        Object.values(OPTION_KEY).map((t: any, i: number) => {
          param.monthEle[i + 1] = parseFloat(
            (parseFloat(item.colData[`${i + 1}月`]) ? item.colData[`${i + 1}月`] : 0) as any,
          ).toFixed(4);
        });
        const res = await saveYearToMonthPowerGenerationPlan(param, curMarketId);
        if (res?.statusCode === HttpCode.SUCCESS) {
          return true;
        }
      });
      setBtnLoding(false);
    } else if (saveType === 2) {
      setBtnLoding(true);
      //月计划
      finalyFile.forEach(async (item: any) => {
        const param: any = {
          monthEle: {},
          stationId: item.unitID,
          valueType: 'numerical',
          year: item.yearDate,
          publish: true,
          yearEle: item.count,
        };
        if (useNewServers.includes(curMarketId)) {
          param.marketId = curMarketId;
        }
        Object.values(OPTION_KEY).map((t: any, i: number) => {
          param.monthEle[i + 1] = _parseFloat(item.colData[`${i + 1}月`], 3);
        });
        const res = await saveYearToMonthPowerGenerationPlan(param, curMarketId);
        if (res?.statusCode === HttpCode.SUCCESS) {
          return true;
        }
      });
      setBtnLoding(false);
    } else {
      setBtnLoding(true);
      //月计划-分段
      finalyFile.forEach(async (item: any) => {
        const param: any = {
          monthEle: {},
          timePlanDetails: item.colData,
          stationId: item.unitID,
          valueType: 'numerical',
          year: item.yearDate,
          publish: true,
          yearEle: item.count,
          marketId: item.marketId,
        };
        const res = await saveYearToMonthPowerGenerationPlan(param, curMarketId);
        if (res?.statusCode === HttpCode.SUCCESS) {
          return true;
        }
      });
      setBtnLoding(false);
    }
    onPress({ index: 1 });
  };
  const downFile = () => {
    form.submit();
  };

  //交易中心改变事件
  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
      setCurMarketId(item.value);
      form.setFieldsValue({
        stationIdList: item.stations.map((v: StationType) => {
          return v.stationId;
        }),
      });
    }
  };
  //月份数据加总
  const monthToYear = (val: any) => {
    if (!val?.length) return '0';
    else
      return val.some((t: any) => t !== null)
        ? _parseFloat(
            val.reduce((a: number, b: number) => a + b),
            3,
          )
        : null;
  };
  function parse(data: number, data_2: number, type: 'add' | 'reduce') {
    switch (type) {
      case 'add':
        return (data * 10000 + data_2 * 10000) / 10000;
      case 'reduce':
        return (data * 10000 - data_2 * 10000) / 10000;
    }
  }
  //月分解比例
  const getNewMonthRadioData = (data: any, date: any) => {
    //月计划
    const radio: any = [];
    //月度分解比例
    Object.entries(data).forEach((t: any) => {
      const _data: any = {
        title: stations.find((_t: any) => _t.stationId === t[0]).label,
      };
      let _temp: any = [];
      Object.entries(t[1].proportion).forEach((_t: any) => {
        Object.entries(_t[1]).forEach((x: any) => {
          let count: any = '',
            title = '';
          const month: any = {};
          if (x[0].includes('plan')) {
            title = _t[0] + '年计划比例(%)';
          }
          if (x[0].includes('operate')) {
            title = _t[0] + '年经营比例(%)';
          }
          if (x[0].includes('guoneng')) {
            title = _t[0] + '年国能日新预测比例(%)';
          }
          if (x[0].includes('huineng')) {
            title = _t[0] + '年金风慧能预测比例(%)';
          }
          if (x[0].includes('settlement')) {
            title = _t[0] + '年结算比例(%)';
          }
          count = monthToYear(x[1]);
          x[1]?.forEach((y: any, i: number) => {
            month[OPTION_KEY[i + 1]] = y !== null ? _parseFloat(y, 4) : y;
          });
          if (count !== null) {
            _temp.push({
              title,
              ...month,
            });
          }
        });
      });
      const str = moment(date).format('YYYY') + '年计划比例(%)';
      const top = _temp.filter((c: any) => c.title === str);
      if (top.length) {
        _temp = _temp
          .map((item: any) => {
            if (item.title === str) {
              let _num = 0;
              //不存在的数据转0
              Object.values(OPTION_KEY).forEach((_t: any) => {
                if (!item[_t]) {
                  item[_t] = 0;
                }
                //总比例超过100% 则最多100%
                if (parse(_num, parseFloat(item[_t] as string), 'add') >= 1) {
                  item[_t] = parse(1, _num, 'reduce');
                  _num = 1;
                } else {
                  _num = parse(_num, item[_t], 'add');
                }
                //最后一个月 总比例仍小于100% 补到十二月
                if (_t === 'December' && _num < 1) {
                  item[_t] = parseFloat(parse(1, _num, 'reduce') as any).toFixed(4);
                }
              });
            }
            return item;
          })
          .sort((a: any, b: any) => {
            return a.title === str ? -1 : b.title.substring(0, 4) - a.title.substring(0, 4);
          });
      } else {
        _temp.unshift({
          title: str,
          January: '0',
          February: '0',
          March: '0',
          April: '0',
          May: '0',
          June: '0',
          July: '0',
          August: '0',
          September: '0',
          October: '0',
          November: '0',
          December: '0',
        });
      }
      _data.data = _temp;
      radio.push(_data);
    });
    return radio;
  };
  //月计划导出
  const monthDeal = (data: any, _date: any, _marketId: any) => {
    return data.map((t: any) => {
      return {
        data: t.data.length
          ? t.data.map((_t: any) =>
              Object.entries(_t)
                .filter((_t_: any) => _t_[0] !== 'count')
                .map((_t_: any) => (_t_[1] === null ? '-' : _t_[1])),
            )
          : [[_date + '年计划电量', ...Object.values(OPTION_KEY).map(() => '-')]],
        sheetName: t.unit,
        header:
          _marketId === 'PXBNX'
            ? [
                '',
                '00:00',
                '01:00',
                '02:00',
                '03:00',
                '04:00',
                '05:00',
                '06:00',
                '07:00',
                '08:00',
                '09:00',
                '10:00',
                '11:00',
                '12:00',
                '13:00',
                '14:00',
                '15:00',
                '16:00',
                '17:00',
                '18:00',
                '19:00',
                '20:00',
                '21:00',
                '22:00',
                '23:00',
              ]
            : ['                       '].concat(
                Object.values(OPTION_KEY).map((_t: any, _i: number) => _i + 1 + '月'),
              ),
        // header: ['                       '].concat(
        //   Object.values(OPTION_KEY).map((_t: any, _i: number) => _i + 1 + '月'),
        // ),
      };
    });
  };
  //年计划导出
  const yearDeal = (data: any, _date: any) => {
    //年计划
    const _temp = data[0].map((item: any) => {
      const _data = Object.entries(item)
        .filter((t: any) => t[0] !== 'status' && t[0] !== 'title' && t[0] !== 'unitId')
        .map((t: any) => {
          let _title = t[0].split('_')[0] + '年';
          if (t[0].includes('plan')) {
            _title += '计划电量';
          } else if (t[0].includes('operate')) {
            _title += '经营电量';
          } else if (t[0].includes('settlement')) {
            _title += '结算电量';
          } else if (t[0].includes('huineng')) {
            _title += '金风慧能预测';
          } else if (t[0].includes('guoneng')) {
            _title += '国能日新预测';
          }
          return [_title, t[1] === null ? '-' : t[1]];
        })
        .sort((a: any, b: any) => {
          return b[0].substring(0, 4) === a[0].substring(0, 4)
            ? a[0].includes('计划')
              ? -1
              : 0
            : b[0].substring(0, 4) - a[0].substring(0, 4);
        });
      return {
        data: _data.length ? _data : [[_date + '年计划电量', '-']],
        sheetName: item.title,
        header: ['                       ', '计划电量'],
      };
    });
    //分解比例
    data[1].forEach((item: any, index: number) => {
      const _data = item.data.map((t: any) => [
        t.title,
        ...Object.values(OPTION_KEY).map((_t: any) => (t[_t] === null ? '-' : t[_t])),
      ]);
      //间隔插入分解比例
      _temp.splice(index * 2 + 1, 0, {
        data: _data.length ? _data : [[_date + '年计划电量', '-']],
        sheetName: item.title + '分解比例',
        header: ['                       '].concat(
          Object.values(OPTION_KEY).map((_t: any, _i: number) => _i + 1 + '月'),
        ),
      });
    });
    return _temp;
  };
  //导出
  const onexport = (data: any, type: any, _date: any, _marketId: any) => {
    if (!data.length) return;
    const hasSave =
      buttonPermissions.filter((item: any) => item.menuCode === 'ContractAnalysisExportButton')
        .length > 0;
    if (!hasSave) {
      return message.info('请联系管理员获取相关权限');
    }
    const filename = `模板`;
    const params: any = {
      list: [],
      name: filename,
      type: 'xlsx',
    };
    if (type == '1') {
      params.list = monthDeal(data, _date, _marketId);
    } else {
      params.list = yearDeal(data, _date);
    }
    export_json_sheets_to_excel(params);
  };
  const _uploadChange = (info: any) => {
    setUploadData(info.fileList);
    if (info.fileList.length) {
      setShowBtn(false);
    } else {
      setFinalyFile([]); //清空已校验场站数据
      setSaveType(0);
      setShowBtn(true);
    }
  };

  const _onFinish = useDebounceFn(
    async (values: any) => {
      // setLoading(true);
      // 查询
      const _marketId = values.marketId;
      const _formData = values,
        _date = moment(_formData.date).format('YYYY'),
        _referenceYear = _formData.referenceYear || [],
        _plan = _formData.plan,
        // _unit = _formData.unit;
        _unit = _formData.stationIdList;
      //参考年份参数
      const referenceYearParams = _referenceYear.map((t: any) => {
        return {
          dataTypeList: ['settlement', 'huineng', 'guoneng', 'plan', 'operate'],
          year: t,
        };
      });
      //请求表格数据
      const param = {
        reqDataScopes: [
          {
            dataTypeList: ['huineng', 'guoneng', 'plan', 'settlement', 'operate'],
            year: _date,
          },
          ...referenceYearParams,
        ],
        respDataTypes: ['numerical', 'proportion'],
        stationIds: _unit,
      };
      //发起请求
      const res = await querypowerGenerationData(param, _marketId);
      if (res?.statusCode === HttpCode.SUCCESS) {
        //处理表格数据
        let data: any = getNewTableData(res.data || {}, _plan, _marketId);
        if (_plan == 0) {
          const radio = getNewMonthRadioData(res.data, _date);
          data = [data.filter((t: any, i: number) => i !== 0), radio];
        }
        if (_marketId === 'PXBNX' && _plan == 0) {
          data[0] =
            data?.[0]?.map((i: any) => {
              const obj: any = {};
              Object.keys(i).forEach((k: any) => {
                if (!k.includes('huineng') && !k.includes('guoneng') && !k.includes('operate')) {
                  obj[k] = i[k];
                }
              });
              return obj;
            }) || [];
        }
        onexport(data, _plan, _date, _marketId);
      }
    },
    { wait: 500 },
  );
  const initialValues = () => {
    return {
      plan: 1,
      date: moment(),
      marketId: province.length > 0 ? province[0].value : '',
    };
  };
  return (
    <Modal
      width={920}
      className={styles.modal}
      centered={true}
      visible={visible}
      maskClosable={true}
      title={
        <div key="title" className={styles.modal_title}>
          导入发电计划
        </div>
      }
      onCancel={_onCancel}
      cancelText={'取消'}
      okText={'确定'}
      onOk={_onOk}
      footer={[
        <Button key="back" onClick={_onCancel}>
          取消
        </Button>,
        saveType !== 0 && (
          <Button key="submit" type="primary" loading={btnLoding} onClick={_onOk}>
            确定
          </Button>
        ),
      ]}
    >
      <Form
        form={form}
        initialValues={initialValues()}
        className={styles.formStyles}
        onFinish={_onFinish.run}
      >
        <Space size={[12, 8]} wrap>
          <Form.Item
            name="plan"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择计划' }]}
          >
            <Select
              style={{ width: 120, fontSize: 12 }}
              placeholder="选择计划"
              options={planOptions}
            />
          </Form.Item>
          {/* <Form.Item
            name="unit"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择交易单元' }]}
          >
            <MyStations
              className={styles.unit}
              options={stations}
              treeData={stationTree}
              optionAll={optionAll}
              width={200}
            />
          </Form.Item> */}

          <Form.Item name="marketId" className={styles.marketId_item}>
            <Select
              options={province}
              style={{ width: 180 }}
              placeholder="请选择交易中心"
              onChange={changeMarketId}
            />
          </Form.Item>

          <Form.Item name="stationIdList" className={styles.marketId_item}>
            <TjMarketingUnit treeData={treeData} marketId={currentProvinceInfo?.value} />
          </Form.Item>

          <Form.Item
            name="date"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择计划年份' }]}
          >
            <DatePicker
              style={{ width: 120 }}
              placeholder="选择计划年份"
              disabledDate={disabledPlanDate}
              onChange={onDateChange}
              picker="year"
            />
          </Form.Item>
          <Form.Item name="referenceYear" className={styles.cell_item}>
            <MySelect style={{ width: 120, fontSize: 12 }} options={referencePowerOption} />
          </Form.Item>
          <div className={styles.down} onClick={downFile}>
            下载模板
          </div>
        </Space>
      </Form>
      <div className={styles.driver} />
      <div className={styles.label}>
        导入文件
        <span className={styles.after}>仅支持Excel文件</span>
      </div>
      <div style={{ width: 180 }}>
        <ConfigProvider locale={zhCN}>
          <Upload
            fileList={uploadData}
            name="file"
            onChange={_uploadChange}
            showUploadList={{
              removeIcon: <CloseOutlined style={{ fontSize: 14 }} />,
            }}
            accept=".xls, .xlsx"
            iconRender={() => <FileTextOutlined style={{ color: '#18A0FB' }} />}
            beforeUpload={_beforeUpload}
          >
            {
              <Button
                style={{ display: !showBtn ? 'none' : 'block' }}
                className={styles.improt_file}
                icon={<DownloadOutlined />}
              >
                导入
              </Button>
            }
          </Upload>
        </ConfigProvider>
      </div>
    </Modal>
  );
};

class ExportModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ExportModal();
